import React, { useEffect, useState } from 'react';
import PropTypes from 'prop-types';
import cn from 'classnames';
import {
	CheckmarkFilled16 as VerifiedIcon,
	WarningFilled16 as NotVerifiedIcon,
} from '@carbon/icons-react';
import fetch from 'API/fetch'
import Button from '@kuiper-components/button';
import Table from '@knownsec/react-component/dist/Table';
import Pagination from '@knownsec/react-component/dist/Pagination';
// import Table from '@kuiper-components/page-table';
import Tooltip from '@kuiper-components/tooltip';
import Loading from '@kuiper-components/loading';
import EmptyData from '../../../../components/empty/EmptyData';
import confirm from '../../../../components/confirm';
import notification from '@kuiper-components/notification';
import CopyBoard from '../../../../components/CopyBoard';

import ReceiverEditor from './ReceiverEditor';
import s from './AlertReceiver.module.css';

export default function AlertReceiver({ className }) {
	// const [selectedRows, setSelectedRows] = React.useState({});
	const { balance } = JSON.parse(sessionStorage.getItem('resD'))
	const alertReceiverBalance = (balance?.alertReceiver?.total - balance?.alertReceiver?.used) > 0 ? (balance?.alertReceiver?.total - balance?.alertReceiver?.used) : 0
	const [selectedRowKeys, setSelectedRowKeys] = React.useState([]);
	const receiverUpdateOne = () => {};
	const [type, setType] = React.useState('empty');
	const [filter, setFilter] = React.useState({
		page: 1,
		pageSize: 10,
	});
	const [data, setData] = useState([])
	const [total, setTotal] = useState(0)
	const [loading, setLoading] = useState(false)
	const getData = (filter) => {
		const { page, pageSize } = filter;
		setLoading(true)
		fetch(`/api/v2/alerts/receivers?page=${page}&pageSize=${pageSize}`, { method: 'GET' }).then(res => {
			if(res.code === 200) {
				const finallyData = res.result.data.map(item => {
					return {...item, key: item.receiver_id }
				})
				setData(finallyData)
				setTotal(res.result.total)
			}
		}).finally(() => {
			setLoading(false)
		})
	}

	const refetch = () => {
		getData({ page: 1, pageSize: 10 });
	};
	React.useEffect(() => {
		if (!loading) setType('img');
	}, [loading]);
	useEffect(() => {
		getData(filter)
	}, [])
	const tooltipCtnRef = React.useRef();

	// const disableRowSelected = data?.defaultReceiver?.reduce((obj, item) => {
	// 	obj[item._id] = true;
	// 	return obj;
	// }, {});

	const dataSource = React.useMemo(() => {
		const dt1 = (data?.defaultReceiver || []).map(item => {
			return { ...item, key: item };
		});
		const dt2 = (data?.unDefaultReceiver || []).map(item => {
			return { ...item, key: item };
		});
		return dt1.concat(dt2);
	}, [data, filter]);

	const tableData = React.useMemo(() => {
		const { page, pageSize } = filter;
		return dataSource.slice((page - 1) * pageSize, page * pageSize);
	}, [filter, dataSource]);

	// const enableBatchDelete = Object.values(selectedRows).some(Boolean);
	const onSelectChange = newSelectedRowKeys => {
		setSelectedRowKeys(newSelectedRowKeys);
	};

	const getCheckbox = record => {
		if (record?.is_default) {
			return { disabled: true };
		} else {
			return null;
		}
	};

	const rowSelection = {
		selectedRowKeys,
		onChange: onSelectChange,
		getCheckboxProps: getCheckbox,
	};
	const getTooltipContainer = () => {
		return tooltipCtnRef.current;
	};

	const handleRemoveMany = receivers => {
		let name = ''
		if (!receivers[0]?.name) {
			data.map(item => {
				if (receivers?.includes(item.receiver_id) && !name) {
					name = item.name
				}
			})
		}
		confirm.warning({
			message: (
				<span>
					删除告警人行为不可逆，您确认要删除
					<mark> {receivers[0]?.name || name} </mark>
					{receivers.length > 1 && '等'}告警人吗？
				</span>
			),
			okText: '删除',
			cancelText: '取消',
			onCancel: () => {
				setSelectedRowKeys([]);
			},
			onOk: () =>
				fetch('/api/v2/alerts/receiver', {
					method: 'DELETE',
					body: JSON.stringify({receiver_ids: name ? receivers : receivers.map(x => x.receiver_id)}),
				})
					.then(() => {
						setFilter({
							page: 1,
							pageSize: 10,
						});
						getData({
							page: 1,
							pageSize: 10,
						})
						setSelectedRowKeys([]);
						notification.success({
							message: '删除告警人成功',
							placement: 'top',
						});
					})
					.catch(err => {
						notification.error({
							message: '删除告警人失败',
							description: err.message,
							placement: 'top',
						});
					}),
		});
	};

	const columns = [
		{
			title: '告警人名称',
			dataIndex: 'name',
			key: 'name',
			render(val) {
				return (
					<div title={val}>
						<CopyBoard text={val} maxWidth="11rem" />
					</div>
				);
			},
		},
		{
			title: '邮箱',
			dataIndex: 'email',
			key: 'email',
			render(email, receiver) {
				if (!email) return '- -';
				if (receiver.email_verified) {
					return (
						<span className={s.contact}>
							<CopyBoard text={email} maxWidth="11rem" />
							<VerifiedIcon className={s.verifiedIcon} />
						</span>
					);
				}
				return (
					<Tooltip
						placement="bottom"
						getTooltipContainer={getTooltipContainer}
						overlay={
							<>
								邮箱未验证，不能接收消息。
								<ReceiverEditor
									type="phone"
									step="verify"
									receiver={receiver}
									emailAutoSend={true}
									receiverUpdateOne={receiverUpdateOne}
								>
									<Button primary link size="small">
										重新验证
									</Button>
								</ReceiverEditor>
							</>
						}
					>
						<span className={s.contact}>
							{email}
							<NotVerifiedIcon className={s.notVerifiedIcon} />
						</span>
					</Tooltip>
				);
			},
		},
		{
			title: '手机',
			dataIndex: 'phone',
			key: 'phone',
			render(phone, receiver) {
				if (!phone) return '- -';
				if (receiver.phone_verified) {
					return (
						<span className={s.contact}>
							{phone}
							<VerifiedIcon className={s.verifiedIcon} />
						</span>
					);
				}

				return (
					<Tooltip
						placement="bottom"
						trigger="hover"
						getTooltipContainer={getTooltipContainer}
						overlay={
							<>
								电话号码未验证，不能接收消息。
								<ReceiverEditor
									type="phone"
									step="verify"
									receiver={receiver}
									phoneAutoSend={true}
									receiverUpdateOne={receiverUpdateOne}
								>
									<Button primary link size="small">
										重新验证
									</Button>
								</ReceiverEditor>
							</>
						}
					>
						<span className={s.contact}>
							{phone}
							<NotVerifiedIcon className={s.notVerifiedIcon} />
						</span>
					</Tooltip>
				);
			},
		},
		{
			title: '操作',
			dataIndex: 'enable',
			key: 'actions',
			// eslint-disable-next-line react/display-name
			render(enable, receiver) {
				return (
					<div className={s.actions}>
						<ReceiverEditor
							step="edit"
							init={0}
							refetch={refetch}
							receiver={receiver}
							nameDisabled={receiver?.is_default}
							receiverUpdateOne={receiverUpdateOne}
						>
							<Button primary link className={s.btn}>
								编辑
							</Button>
						</ReceiverEditor>
						{!receiver?.is_default && (
							<Button
								primary
								link
								className={cn(s.btn, s.ml16)}
								onClick={() => handleRemoveMany([receiver])}
							>
								删除
							</Button>
						)}
					</div>
				);
			},
		},
	];

	return (
		<div className={cn(className, s.alertReceiver)} ref={tooltipCtnRef}>
			<div className={s.toolbox}>
				<ReceiverEditor
					init={1}
					refetch={refetch}
					receiverUpdateOne={receiverUpdateOne}
					alertReceiverBalance={alertReceiverBalance}
				>
					<Button primary>添加告警人</Button>
				</ReceiverEditor>
				<div className={s.balanceDescription}>
					您当前已创建<mark>{total}</mark>个告警人，还可创建
					<mark>{alertReceiverBalance}</mark>个告警人。
				</div>
			</div>
			<div className={s.mt1rem}>
				<Table
					empty={<EmptyData type={type} className={s.nobor} />}
					loading={loading}
					columns={columns}
					data={data}
					className={s.newtable}
					pro
					rowSelection={rowSelection}
				/>
			</div>
			{/* <Table
					alwaysShowPagination
					className={s.table}
					routePrefix={routePrefix}
					columns={columns}
					type="local"
					data={dataSource}
					rowSelected={selectedRows}
					onRowSelectionChange={setSelectedRows}
					disableRowSelected={disableRowSelected}
				/> */}
			<div className={cn('df aic jcsb mt5')} style={{paddingRight: '24px'}}>
				<Button
					link
					className={s.batchRemove}
					disabled={!selectedRowKeys.length}
					onClick={() => handleRemoveMany(selectedRowKeys)}
				>
					批量删除
				</Button>
				<Pagination
					current={filter.page || 1}
					pageSizeOptions={[10, 20, 50]}
					showSizeChanger
					showQuickJumper
					showTotal={total => `共${total}条`}
					total={total}
					onChange={(page, pageSize) => {
						const obj = Object.assign({}, filter);
						obj.page = page;
						obj.pageSize = pageSize;
						setFilter(obj);
						getData(obj)
					}}
				/>
			</div>
		</div>
	);
}

AlertReceiver.propTypes = {
	className: PropTypes.string,
};

AlertReceiver.defaultProps = {
	className: s.AlertReceiver,
};
